import * as Ladda from './ladda.js';
$(function(){
	/*value：表示当前单元格中的值
	row：表示当前行
	index：表示当前行的下标*/
	function operateFormatter(value, row, index) {
	    return [
	    	'<button class="btn btn-danger update" data-toggle="modal" data-target="#editModal">修改</button>  ',
			'<button class="btn btn-danger remove" data-toggle="modal" data-target="#confirmModal">删除</button>'
	    ].join('')
	}
	
	//当值为0或null时显示无
	function CustomFormatter(value, row, index){
		if(value == 0 || value == null){
			return '无';
		}else{
			return value;
		}
	}
	
	//表格操作
	window.operateEvents = {
		//修改
		'click .update': function (e, value, row, index) {
			$(".input-name").val(row.name);
			$(".input-version").val(row.version);
			$("input:hidden[id='updateId']").val(row.id);
			$("input:hidden[id='codeType']").val(row.codeType);
		},
		    
		//删除
		'click .remove': function (e, value, row, index) {
			$("input:hidden[id='deleteId']").val(row.id);
			$("#confirmModalMessage").text("确认删除"+row.name+"?");
		}
	}
	
	//bootstrap-table配置
	$('#mytab').bootstrapTable({
	    url: '/resource/userResource',
	    toolbar: "#toolbar",
	    toolbarAlign:'right',
	    sidePagination: "server",
	    striped: true, // 是否显示行间隔色
	    pageNumber : 1, 
	    pageSize: 8,
	    pageList: [8, 25],
	    pagination: true, // 是否分页
	    sortable: true, // 是否启用排序
	    queryParams: function(params) {//上传服务器的参数
	        var temp = {
	        	pageNum : this.pageNumber,  
	        	pageSize : this.pageSize,
	        	name: $("#resourceName").val(),
	        	startTime: $("#startTime").val(),
	        	endTime: $("#endTime").val()
	        };
	        return temp;
	    },
	    columns: [
	    	{
	            field: 'name',
	            title: '资源名称',
	            formatter: CustomFormatter
	        },
	        {
	            field: 'version',
	            title: '版本号',
	            formatter: CustomFormatter
	        },
	        {
	            field: 'bookCodeStart',
	            title: '开始码',
	            formatter: CustomFormatter
	        },
	        {
	            field: 'bookCodeEnd',
	            title: '结束码',
	            formatter: CustomFormatter
	        },
	        {
	            field: 'updatedAt',
	            title: '更新时间',
	            formatter: CustomFormatter
	        },
	        {
	            field: '',
	            title: '操作',
	            align: 'center',
	            valign: 'middle',
	            formatter: operateFormatter,
	            events: window.operateEvents
		    },
		]
	});
	
	//查询
	$(document).on('click', "#searchBtn",function(){
	     $('#mytab').bootstrapTable('selectPage', 1, 'refresh');
	     $('#searchModal').modal('hide');
	});
	
	// 时间
	$(".form_datetime").datetimepicker({
	    format: "yyyy-mm-dd hh:ii",
	    language: 'zh-CN',
	    autoclose: 1, //选择后自动关闭
	    clearBtn:true //清除按钮
	});
	// 清除文本框焦点
	document.getElementsByClassName('form_datetime')[0].addEventListener('click', function(e){
		e.currentTarget.blur();
	})
	document.getElementsByClassName('form_datetime')[1].addEventListener('click', function(e){
		e.currentTarget.blur();
	})
	
	$('input[type=radio][name=codeOptions]').change(function() {
	     if (this.value == '2') {
	         $("#code-div").css('display','block');
	     }else{
	    	 $("#code-div").css('display','none');
	     }
	 });
	
	//限制手动输入码是数字
	$('#codeInput').keyup(function(){
		var value = $(this).val();
		$(this).val(value.replace(/[^\d]/g,''))
	})
	
	//截取文件名
	function getFileName(file){
		var start = file.lastIndexOf("\\");//查找最后一个\的位置
	//	var stop = file.lastIndexOf(".");//查找最后一个.的位置
		return file.substring(start+1);
	}
	
	// 定义jQuery 自己的 XMLHttpRequest 对象，停止上传调用
	var jqXHR;
	//初始化上传插件
	$("#fileupload").fileupload({
		type: 'PUT',
		contentType: 'application/octet-stream',
		multipart: false,
		//autoUpload:是否自动上传，即当文件放入file之后便自动上传，默认为true
	    autoUpload: false,
	    maxNumberOfFiles : 1,
	    //添加文件后触发
	    add: function (ev, data) {
	    	$("#uploadBtn").off("click").click(function () {
	    		$("#uploadBtn").attr({ disabled: "disabled" });
	    		$("#uploadBtn").text("正在请求上传");
	    		readFile(data);
	        });
	    	$("#cancelBtn").off("click").click(function () {
	    		jqXHR.abort();
	    		$(".progress").css('display','none');
				$("#cancelBtn").css('display','none');
				$("#uploadBtn").text("确定上传");
		    	$("#uploadBtn").css('display','block');
		    	$("#uploadBtn").removeAttr("disabled");
	        });
	    },
	    progressall: function(e, data) {
			var progress = parseInt(data.loaded / data.total * 100, 10);
			$(".progress").css('display','block');
			$(".progress-bar").css('width',progress+'%');
			if(progress == 100){
				$(".progress").css('display','none');
				$("#cancelBtn").css('display','none');
				$("#uploadBtn").text("确定上传");
		    	$("#uploadBtn").css('display','block');
		    	$("#uploadBtn").removeAttr("disabled");
			}
		},
	    // 上传请求成功时触发的回调函数，如果服务器返回一个带有error属性的json响应这个函数也会被触发
	    done: function (e, data) {
	    	//上传到数据库
	    	$.ajax({
	    		type: "post",
	    		url: "/resource/insert",
	    		async: false,
	    		data: {
	    			name: data.context.name,
	    			ossObject: data.context.ossObject,
	    			bookCodeStart: data.context.bookCodeStart,
	    			bookCodeEnd: data.context.bookCodeEnd,
	    			codeType: data.context.codeType
	    		},
	    		success: function(result){
	    			console.log(result)
	    			if(result.code == 0){
	    				console.log("上传到数据库成功");
	    				window.location.reload()//刷新当前页面
	    			}else{
	    				 alert(result.message);
	    			}
	    		}
	    	})
	    },
	    //上传请求失败时触发的回调函数，如果服务器返回一个带有error属性的json响应这个函数将不会被触发
	    fail: function (e, data) {
	    	$("#uploadBtn").removeAttr("disabled");
	    	if (data.errorThrown=='abort') {
	    		$("#newModal").modal("toggle");
	    		$("#cancelModal").modal("toggle");
	        }else{
	            alert("文件上传失败,请检查");
	        }
	    },
	    
	})
	
	//读取文件
	var readFile = function(fileData){
		var file = fileData.files[0];
		//文件名字
		var filename = getFileName(file.name);
		//开始码
		var bookCodeStart = 0; 
		//结束码
		var bookCodeEnd = 0;
		//服务器返回的签名url
		var url = null;
		
		if(file != null){
			//读取资源文件
			var reader = new FileReader();
			reader.readAsArrayBuffer(file);
			
			//读取成功执行
			reader.onload = function(){
				//将读取的数据保存到Uint8Array数组
				var byts = new Uint8Array(this.result);
				//移几个字节
				var temp = 0;
				//获取单选框的值
				var codeType = $("input[name='codeOptions']:checked").val();
				if(codeType == 1){
					//区间码解析
					//读取位置
					var start = parseInt('0xD6',16);//214
					//从start开始读取4个字节
					for(var i = start;i < start+8;i++){
						
						if(i < start+4){
							bookCodeStart += byts[i]<<temp*8;
						}else{
							if(i == start+4){
								temp = 0;//重置
							}
							bookCodeEnd += byts[i]<<temp*8;
						}
						temp++;
					}
				}else{
					//固定码解析
					var codeInput = $("#codeInput").val();
					if(codeInput != null && codeInput != ''){
						console.log("手动输入...")
						// 用户手动输入固定码
						bookCodeStart = codeInput;
					}else{
						console.log("自动读取...")
						//读取位置
						var start = parseInt('0x01D8',16);//472
						//从start开始读取4个字节
						for(var i = start;i < start+4;i++){
							bookCodeStart += byts[i]<<temp*8;
							temp++;
						}
					}
				}
				
	//			bookCodeStart = bookCodeStart>>>0
	//			bookCodeEnd = bookCodeEnd>>>0
				bookCodeStart = bookCodeStart & 0xFFFFFFFF
				bookCodeEnd = bookCodeEnd & 0xFFFFFFFF
				
				//发送请求到服务器获取签名等信息
				$.ajax({
					type : "post",
					url : "/aliyun/oss/policy",
					async: false,
					data : {
						name:filename,
						bookCodeStart:bookCodeStart,
						bookCodeEnd:bookCodeEnd,
						codeType:codeType
					},
					success : function(result){
						console.log(result)
						if(result.code == 0){
							fileData.url = result.data.url;
							fileData.context = result.data.resource;
							$("#uploadBtn").css('display','none');
							$("#cancelBtn").css('display','block');
							jqXHR = fileData.submit();
						}else{
							$("#uploadBtn").text("确定上传");
							$("#uploadBtn").removeAttr("disabled");
							//oss已存在文件
							alert(result.message);
						}
						
					}
				})
				
			}//reader.onload
			
		}else{
			alert("请选择需要上传的资源文件");
		}
	}
	
	
	//初始化更新上传插件
	$("#fileupdate").fileupload({
		type : "PUT",
		contentType: 'application/octet-stream',
		multipart: false,
	    autoUpload: false,
	    maxNumberOfFiles : 1,
	    add: function (ev, data) {
	    	$("#fileupdateBtn").off("click").click(function () {
	    		$("#fileupdateBtn").attr({ disabled: "disabled" });
	    		$("#fileupdateBtn").text("正在请求上传");
	    		fileUpdate(data);
	        });
	    	$("#cancelupdateBtn").off("click").click(function () {
	    		jqXHR.abort();
	    		$(".progress").css('display','none');
				$("#cancelupdateBtn").css('display','none');
				$("#fileupdateBtn").text("确定上传");
		    	$("#fileupdateBtn").css('display','block');
		    	$("#fileupdateBtn").removeAttr("disabled");
	        });
	    },
	    progressall: function(e, data) {
			var progress = parseInt(data.loaded / data.total * 100, 10);
			$(".progress").css('display','block');
			$(".progress-bar").css('width',progress+'%');
			if(progress == 100){
				$(".progress").css('display','none');
				$("#cancelupdateBtn").css('display','none');
				$("#fileupdateBtn").text("确定上传");
		    	$("#fileupdateBtn").css('display','block');
		    	$("#fileupdateBtn").removeAttr("disabled");
			}
		},
	    done: function (e, data) {
	    	//更新数据库
	    	$.ajax({
	    		type: "post",
	    		url: "/resource/update",
	    		async: false,
	    		data: {
	    			id: data.context.id,
	    			name: data.context.name,
	    			ossObject: data.context.ossObject
	    		},
	    		success: function(result){
	    			console.log(result)
	    			if(result.code == 0){
	    				console.log("更新到数据库成功");
	    				window.location.reload()//刷新当前页面
	    			}else{
	    				 alert(result.message);
	    			}
	    		}
	    	})
	    },
	    fail: function (e, data) {
	    	$("#fileupdateBtn").removeAttr("disabled");
	    	if (data.errorThrown=='abort') {
	   		 	$("#editModal").modal("toggle");
	   		 	$("#cancelModal").modal("toggle");
	        }else{
	            alert("文件更新失败,请检查");
	        }
	    },
	})
	
	//更新文件
	var fileUpdate = function(fileData){
		var resourceId = $("input:hidden[id='updateId']").val();
		var file = fileData.files[0];
		var filename = getFileName(file.name);
		
		if(file != null){
			$.ajax({
				type: "post",
				url: "/aliyun/oss/update",
				data:{
					id: resourceId,
					name:filename
				},
				success:function(result){
					if(result.code == 0){
						fileData.url = result.data.url;
						fileData.context = result.data.resource;
						$("#fileupdateBtn").css('display','none');
						$("#cancelupdateBtn").css('display','block');
						jqXHR = fileData.submit();
					}else{
						$("#fileupdateBtn").text("确定上传");
						$("#fileupdateBtn").removeAttr("disabled");
					}
				}
			})
		}
		
	}
	
	
	//删除资源
	$("#btn-delete").click(function(){
		var resourceId = $("input:hidden[id='deleteId']").val();
		var l = Ladda.create(this);
		
		$.ajax({
			type:"post",
			url:"/aliyun/oss/delete",
			data:{id:resourceId},
			beforeSend: function () {
		 		$(".ladda-delete").text("正在请求服务器");
		 	 	l.start();
		    },
		    complete: function () {
		    	$(".ladda-delete").text("删除");
		    	l.stop();
		    },
			success:function(result){
				if(result.code == 0){
					window.location.reload()//刷新当前页面
				}else{
					 alert(result.message);
				}
				
			}
		})
	})
})	
